﻿using System.Collections.Generic;
using UnityEngine;

public static partial class Extensions
{
    #region 随机

    /// <summary>
    /// 从数组中随机取一个元素
    /// </summary>
    public static T RandomElement<T>(this T[] array)
    {
        return Tools.RandomElement(array);
    }

    /// <summary>
    /// 从数组中随机取一个元素
    /// </summary>
    public static T RandomElement<T>(this IList<T> list)
    {
        return Tools.RandomElement(list);
    }

    /// <summary>
    /// 从数组中随机取出任意数量的不同元素
    /// </summary>
    public static List<T> RandomSubList<T>(this List<T> list, int count)
    {
        return Tools.RandomSubList(list, count);
    }

    #endregion

    #region 拷贝

    /// <summary>
    /// 数组浅拷贝
    /// </summary>
    public static List<T> Clone<T>(this List<T> list)
    {
        return new List<T>(list);
    }

    /// <summary>
    /// 字典浅拷贝
    /// </summary>
    public static Dictionary<TKey, TValue> Clone<TKey, TValue>(this Dictionary<TKey, TValue> dict)
    {
        return new Dictionary<TKey, TValue>(dict);
    }

    // 深拷贝使用Object的方法所以省去
    //public static T CloneDeep<T>(this T obj)
    //{
    //    return obj.ToJson().ToObject<T>();
    //}

    #endregion

    #region 安全修改

    /// <summary>
    /// 安全获取
    /// </summary>
    public static T GetSavely<T>(this IList<T> list, int index)
    {
        if (list == null || list.Count == 0 || index >= list.Count)
            return default;
        return list[index];
    }

    /// <summary>
    /// 安全添加（值为int类型的计数类dict专用）
    /// </summary>
    public static void AddSavely<TKey>(this Dictionary<TKey, int> dict, TKey key, int count)
    {
        if (dict.ContainsKey(key))
            dict[key] += count;
        else
            dict[key] = count;
    }

    /// <summary>
    /// 安全添加（值为float类型的计数类dict专用）
    /// </summary>
    public static void AddSavely<TKey>(this Dictionary<TKey, float> dict, TKey key, float value)
    {
        if (dict.ContainsKey(key))
            dict[key] += value;
        else
            dict[key] = value;
    }

    #endregion
}